package com.kk.permission.checker;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;

import androidx.core.content.PermissionChecker;

import com.kk.permission.PermissionGuideGenerator;
import com.kk.permission.adapter.PermissionAdapter;

import java.util.List;

public class PermissionUtil {
    public static boolean isPermissionGranted(String permission) {
        // For Android < Android M, self permissions are always granted.
        boolean result = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (21 >= Build.VERSION_CODES.M) {
                // targetSdkVersion >= Android M, we can
                // use Context#checkSelfPermission
                result = PermissionAdapter.getAdapter().getAppContext().checkSelfPermission(permission)
                        == PackageManager.PERMISSION_GRANTED;
            } else {
                // targetSdkVersion < Android M, we have to use PermissionChecker
                if(permission.equals(Manifest.permission.WRITE_SETTINGS))
                    return Settings.System.canWrite(PermissionAdapter.getAdapter().getAppContext());
                else
                    result = PermissionChecker.checkSelfPermission(PermissionAdapter.getAdapter().getAppContext(), permission)
                            == PermissionChecker.PERMISSION_GRANTED;
            }
        }

        return result;
    }

    private static int checkSelfPermission(Context context, String str) {
        try {
            return PermissionChecker.checkSelfPermission(context, str);
        } catch (RuntimeException unused) {
            return -1;
        }
    }

    public static boolean isNeedDoPermission(Context context) {
        List permissionList = PermissionGuideGenerator.generateGuideStratagy(context).getPermissionList();
        if (permissionList == null || permissionList.size() == 0) {
            return false;
        }
        return true;
    }
}